import { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import $ from '../../axios'
const fetchList = createAsyncThunk(
    'fetchList',
    async (str, { rejectWithValue }) => {
        try {
            const response = await $.post('/gethomegood', str);
            return response.data;
        } catch (error) {
            return rejectWithValue(error);
        }
    }
);

const fetchComments = createAsyncThunk(
    'fetchComments',
    async (_, { rejectWithValue }) => {
        try {
            const response = await $.get('/getComment');
            return response.data;
        } catch (error) {
            return rejectWithValue(error);
        }
    }
);

const fetchTopic = createAsyncThunk(
    'fetchTopic',
    async (_, { rejectWithValue }) => {
        try {
            const response = await $.get('/getTopic');
            return response.data;
        } catch (error) {
            return rejectWithValue(error);
        }
    }
);

const stateSlice = createSlice({
    name: 'state',
    initialState: {
        detail: [],
        list: [],
        comments: [],
        topic: [],
        guang: []
    },
    reducers: {
        setguang(state, { payload }) {
            state.guang.push(payload)
        },
        getguang(state, { payload }) {
            console.log(111);
        },
        goDetail: (state, action) => {
            state.detail = [action.payload];
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchList.pending, (state, action) => {
                // 处理请求pending状态，比如显示加载指示器  
                // console.log('Fetching list...');
            })
            .addCase(fetchList.fulfilled, (state, action) => {
                state.list = action.payload.homegood;
                // console.log('List fetched successfully:', action.payload);
            })
            .addCase(fetchList.rejected, (state, action) => {
            })
            .addCase(fetchComments.pending, (state, action) => {
            })
            .addCase(fetchComments.fulfilled, (state, action) => {
                state.comments = action.payload.data;
            })
            .addCase(fetchComments.rejected, (state, action) => {
            })
            .addCase(fetchTopic.pending, (state, action) => {
            })
            .addCase(fetchTopic.fulfilled, (state, action) => {
                state.topic = action.payload.data;
            })
            .addCase(fetchTopic.rejected, (state, action) => {
            });
    },
});

const store = configureStore({
    reducer: stateSlice.reducer,
});

export const { goDetail, setMyid, setguang, getguang } = stateSlice.actions;
export { fetchList, fetchComments, fetchTopic };
export default store;